package com.llc.mall.user.infrastructure.gatewayimpl;

import com.llc.mall.common.core.exception.Mall4cloudException;
import com.llc.mall.common.core.response.ServerResponseEntity;
import com.llc.mall.user.domain.share.Token;
import com.llc.mall.user.domain.user.entity.User;
import com.llc.mall.user.domain.gateway.AccountGateway;
import com.mall4j.cloud.api.auth.bo.UserInfoInTokenBO;
import com.mall4j.cloud.api.auth.constant.SysTypeEnum;
import com.mall4j.cloud.api.auth.feign.AccountFeignClient;
import com.mall4j.cloud.api.auth.vo.TokenInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AccountGatewayImpl implements AccountGateway {

    private final AccountFeignClient accountFeignClient;

    public AccountGatewayImpl(AccountFeignClient accountFeignClient) {
        this.accountFeignClient = accountFeignClient;
    }

    @Override
    public Token storeToken(User user) {
        // 2. 登录
        UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
        userInfoInTokenBO.setUid(user.getAccountId());
        userInfoInTokenBO.setUserId(user.getId());
        userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInTokenBO.setIsAdmin(0);
        ServerResponseEntity<TokenInfoVO> result = accountFeignClient.storeTokenAndGetVo(userInfoInTokenBO);
        if (result.isSuccess()) {
            TokenInfoVO tokenInfoVO = result.getData();
            return new Token(tokenInfoVO.getAccessToken(), tokenInfoVO.getRefreshToken(), tokenInfoVO.getExpiresIn());
        } else {
            throw new Mall4cloudException("token 获取异常!");
        }
    }
}
